package com.btashov.linkedlist;

import com.btashov.datastructure.Node;


/**
 * todo: 2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
 * <p/>
 * EXAMPLE
 * <p/>
 * Input: the node ‘c’ from the linked list a->b->c->d->e
 * <p/>
 * Result: nothing is returned, but the new linked list looks like a->b->d->e
 */
public class Removal {

    /**
     * Simply copy the data from the next node into this node and then delete the next node.
     * NOTE: This problem can not be solved if the node to be deleted is the last node in the linked list.
     *
     * @param node Node
     * @return boolean result of deletion
     */
    public static boolean deleteNode(Node node) {
        if (node == null || node.getNext() == null) {
            return false; // Failure
        }
        Node next = node.getNext();
        node.setData(next.getData());
        node.setNext(next.getNext());
        return true;
    }

    public static boolean deleteLastNode(Node n) {
        if (n.getNext() == null) {
            return false;   //cannot delete the last node
        } else {
            n.setData(n.getNext().getData());
            n.setNext(n.getNext().getNext());
        }
        return true;
    }
}
